package com.qitmiaojie.controller;


import cn.hutool.json.JSONUtil;

import com.qitmiaojie.face.Api.Sample;

import com.qitmiaojie.face.response.Result;
import com.qitmiaojie.face.utils.BASE64;
import com.qitmiaojie.pojo.User;
import com.qitmiaojie.service.UserService;
import com.qitmiaojie.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LeiFengLiang
 * @Description: TODO
 * @Classname: PhotoController
 * @date 2022-05-07 15:58
 */

@RestController
@CrossOrigin

@Slf4j
public class PhotoController {


    @Value("${photo.path}")
    private String photo;

    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    UserService userService;

    /**
     * @Description 人脸信息注册
     * @Date 2022/7/16 16:51
     * @Param [file, request]
     * @return void
     **/
    @PostMapping("/werkLogin")
    @ResponseBody
    public void werkLogin(@RequestParam("file")  MultipartFile file, HttpServletRequest request, HttpServletResponse httpServletResponse) throws IOException {
        // 传入可选参数调用接口
        HashMap<String, Object> options = new HashMap<String, Object>();
        options.put("max_face_num", "3");
        options.put("match_threshold", "80");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "NONE");
        options.put("max_user_num", "3");
        String image = getimages(file,request);
        String imageType = "BASE64";
        String groupIdList = "group1";
        // 人脸搜索 M:N 识别
        JSONObject res = Sample.getTAipFace().multiSearch(image, imageType, groupIdList, options);
        System.out.println(res.toString(2));
        int id;
        User user=null;
        try {
            id= res.getJSONObject("result").getJSONArray("face_list")
                    .getJSONObject(0).getJSONArray("user_list")
                    .getJSONObject(0).getInt("user_id");
            user= userService.getById(id);
        }catch (Exception e){
            System.err.println("登入失败，图像不合格");
        }
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
        //生成jwt，并放置到请求头中
        Map<String, Object> map=new HashMap<>();
        map.put("username",user.getUserName());//从security框架中拿取用户名
        //map.put("id",authentication.getDetails()
        String Token=jwtUtils.getToken(map);
        //System.out.println(Token);
        //httpServletResponse.setHeader("Token",Token);
        com.qitmiaojie.controller.utils.Result result=new com.qitmiaojie.controller.utils.Result(200,"登录成功",Token);
        servletOutputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        servletOutputStream.flush();
        servletOutputStream.close();
    }

    /**
     * @Description 人脸信息注册
     * @Date 2022/5/16 16:51
     * @Param [file, request]
     * @return void
     **/
    @PostMapping("/registered")
    @ResponseBody
    public Result registered(@RequestParam("file")  MultipartFile file
                            , HttpServletRequest request
                            /* @RequestParam("id") String id*/
                             ) throws IOException {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = null;
        if (principal instanceof UserDetails) {
            username= ((UserDetails)principal).getUsername();
            log.info("username = " + username);
        } else {
             username = principal.toString();
            log.info("username = " + username);
        }
        User user = userService.getByUsername(username);
        log.info(user.toString());
        log.info("{},{},{}",file.toString(),request);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user's info");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "NONE");
        options.put("action_type", "REPLACE");
        String image = getimages(file,request);
        String imageType = "BASE64";
        String groupId = "group1";
        String userId = user.getId().toString();
        // 人脸注册
        JSONObject res = Sample.getTAipFace().addUser(image, imageType, groupId, userId, options);
        System.out.println(res.toString(2));
        return Result.ok().data("data",res.get("result").toString());
    }


    /**
     * @Description 返回图片
     * @Date 2022/5/18 16:00
     * @Param [file, request]
     * @return java.io.File
     **/
    public String getimages(MultipartFile file, HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request;
        MultipartFile headerImage = multipartRequest.getFile("file");

        if (headerImage == null) {
            System.out.println("您还没有选择图片");
        }

        String  fileName= headerImage.getOriginalFilename();

        //根据当前时间生成文件名
        fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + "." + fileName;
        //System.out.println(fileName);
        // 确定文件存放的路径
        File dest = new File(photo + "/" + fileName);
        try {
            headerImage.transferTo(dest); // 存储文件
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败,服务器发生异常!", e);
        }
        return BASE64.encodeImgageToBase64(dest);
    }

    @RestController
    @Slf4j
    @RequestMapping("/Material")
    public static class MaterialController {



        //领取物资



        //新增物资



    }
}
